package com.huoniu.common.core;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonStreamContext;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.JsonNodeType;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;

import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Collection;

/**
 * @类 名： BaseEnumDeserializer <br/>
 * @描 述： <br/>
 * @日 期： 2020/9/27 15:28<br/>
 * @作 者： 侯建军<br/>
 * @版 本： 1.0.0
 * @since JDK 1.8
 */
@Slf4j
public class BaseEnumDeserializer extends JsonDeserializer<BaseEnum> {

    @SuppressWarnings({"unchecked", "rawtypes"})
    @Override
    public BaseEnum deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
        // 获取节点
        JsonNode node = jp.getCodec().readTree(jp);
        // 获取枚举名称
        String currentName = jp.currentName();
        // 获取当前所在对象
        Object currentValue = jp.getCurrentValue();
        log.info("name:"+currentValue);
        Class findPropertyType = null;
        // 判断当前对象是否是集合
        if (currentValue instanceof Collection) {
            JsonStreamContext parsingContext = jp.getParsingContext();
            JsonStreamContext parent = parsingContext.getParent();
            Object currentValue3 = parent.getCurrentValue();
            String currentName3 = parent.getCurrentName();
            try {
                Field listField = currentValue3.getClass().getDeclaredField(currentName3);
                ParameterizedType listGenericType = (ParameterizedType) listField.getGenericType();
                Type listActualTypeArguments = listGenericType.getActualTypeArguments()[0];
                findPropertyType = (Class) listActualTypeArguments;
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            // 获取原型对象
            findPropertyType = BeanUtils.findPropertyType(currentName, currentValue.getClass());
        }
        if (findPropertyType == null) {
            System.out.println("数据格式异常");
        }

        String name = null;
        System.out.println(node.getNodeType());
        if (node.getNodeType() == JsonNodeType.STRING) {
            name = node.asText();
        } else {
            // 获取枚举对象名称
            name = node.get("name").asText();

        }
        BaseEnum valueOf = null;
        if (StringUtils.isNotBlank(name)) {
            // 查找当前类的枚举名称name的属性
            valueOf = BaseEnum.valueOf(name, findPropertyType);
        }
        return valueOf;
    }
}
